﻿using JiebaNet.Segmenter;
using star_questionnair.Models;
using star_questionnair.Models.Enum;

namespace star_questionnair.Services.impl;

public class WordCloudService : IWordCloudService
{
    private readonly IHistoryService _historyService;
    private readonly IQuestionService _questionService;
    private readonly IAnswerService _answerService;

    private static readonly HashSet<string> STOPWORDS = new HashSet<string>
    {
        "的", "是", "了", "我", "在", "不", "有", "他", "这", "也", "就", "到", "和", "说", "要", "去",
        "你", "会", "吗", "什么", "那", "我们", "可以", "她", "他们", "但", "与", "一个", "而", "人",
        "好", "都", "很", "还是", "没有", "并", "被", "着", "自己", "这个", "下", "一个", "中", "上",
        "还", "为", "对", "以", "来", "这", "想", "，", "。", "想起"
    };

    public WordCloudService(IHistoryService historyService, IQuestionService questionService, IAnswerService answerService)
    {
        _historyService = historyService;
        _questionService = questionService;
        _answerService = answerService;
    }

    // 词云算法
    public async Task<Dictionary<string, int>> GenerateWordFrequencies(int questionId)
    {
        var question = await _questionService.GetQuestionByIdAsync(questionId);
        if (!QuestionEnumExtensions.IsTextType(question.Type))
            return null;

        var answers = _historyService.GetAnswersByQuestionId(questionId);
        var answerContents = answers.Select(a => a.Content).ToList();

        var wordCountMap = new Dictionary<string, int>();

        try
        {
            // 组合所有回答内容
            string text = string.Join(" ", answerContents);

            // 分词
            var segmenter = new JiebaSegmenter();
            var tokens = segmenter.CutForSearch(text).ToList();

            // 统计词频
            foreach (var token in tokens)
            {
                string word = token;
                if (!STOPWORDS.Contains(word) && word.Trim().Length > 0)
                {
                    if (wordCountMap.ContainsKey(word))
                    {
                        wordCountMap[word]++;
                    }
                    else
                    {
                        wordCountMap[word] = 1;
                    }
                }
            }

            // 排序并限制词云大小
            return wordCountMap.OrderByDescending(kv => kv.Value)
                .Take(20)
                .ToDictionary(kv => kv.Key, kv => kv.Value);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }

        return wordCountMap;
    }

    public async Task<Dictionary<bool, Dictionary<string, int>>> GenerateGenderSpecificWordCloud(int questionId)
    {
        var question = await _questionService.GetQuestionByIdAsync(questionId);
        if (!QuestionEnumExtensions.IsTextType(question.Type))
            return null;

        // 获取该问题的所有回答
        var answers = _historyService.GetAnswersByQuestionId(questionId);

        // 按性别分组
        var genderedAnswers = answers.GroupBy(a =>
            {
                var user = _answerService.GetUserByAnswer(a);
                return user.Gender; // 假设 User 对象有 Gender 属性，true 表示男性，false 表示女性
            })
            .ToDictionary(
                g => g.Key,
                g => g.Select(a => a.Content).ToList()
            );

        var genderedWordClouds = new Dictionary<bool, Dictionary<string, int>>();

        try
        {
            // 分别处理男性和女性的回答
            foreach (var entry in genderedAnswers)
            {
                var combinedText = string.Join(" ", entry.Value);

                // 分词
                var segmenter = new JiebaSegmenter();
                var tokens = segmenter.CutForSearch(combinedText).ToList();

                // 统计词频
                var wordCountMap = new Dictionary<string, int>();
                foreach (var token in tokens)
                {
                    string word = token;
                    if (!STOPWORDS.Contains(word) && word.Trim().Length > 0)
                    {
                        if (wordCountMap.ContainsKey(word))
                        {
                            wordCountMap[word]++;
                        }
                        else
                        {
                            wordCountMap[word] = 1;
                        }
                    }
                }

                // 排序并限制词云大小
                var sortedWordCountMap = wordCountMap.OrderByDescending(kv => kv.Value)
                    .Take(20)
                    .ToDictionary(kv => kv.Key, kv => kv.Value);

                genderedWordClouds[entry.Key] = sortedWordCountMap;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }

        return genderedWordClouds;
    }

    public Dictionary<Option, Dictionary<bool, int>> GetGenderDifference(int questionId)
    {
        // 获取该问题的所有选项
        var options = _historyService.GetOptionsByQuestionId(questionId);
        var result = new Dictionary<Option, Dictionary<bool, int>>();

        foreach (var option in options)
        {
            // 初始化选项差异化
            var difference = new Dictionary<bool, int>();
            var answers = _answerService.GetAnswersByOptionId(option.Id);

            foreach (var a in answers)
            {
                // 该答案关联的用户
                var user = _answerService.GetUserByAnswer(a);

                if (difference.ContainsKey(user.Gender))
                {
                    difference[user.Gender]++;
                }
                else
                {
                    difference[user.Gender] = 1;
                }
            }

            result[option] = difference;
        }

        return result;
    }

    // 计算每个文本问题的平均文本量
    public async Task<double?> GetAverageWordOfQuestion(int questionId)
    {
        // 获取问题信息
        var question = await _questionService.GetQuestionByIdAsync(questionId);
        // 检查问题类型是否是简答题或文本域
        if (!QuestionEnumExtensions.IsTextType(question.Type))
        {
            // 不是简答题或文本域，退出
            return null;
        }

        // 获取该问题的所有答案
        var answers = _historyService.GetAnswersByQuestionId(questionId);

        // 计算所有答案的平均字数
        var averageWordCount = answers.Average(a => a.Content.Length);

        // 返回平均字数
        return averageWordCount;
    }
}